package com.lemo.demo.hadoop;

import java.io.IOException;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.IntWritable.Comparator;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.RawComparator;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import com.lemo.demo.hadoop.model.WirtePair;

/**
 * Hello world!
 *
 */
public class MapReduceApp3 extends Configured implements Tool
{
    public static void main( String[] args ) throws Exception
    {
    	args = new String[]{ //
    			"/user/beifeng/tmp2" ,//
    			"/user/beifeng/output2"
    		};
    	Configuration conf = new Configuration();
    	int status = ToolRunner.run(conf, new MapReduceApp3(), args);
    	System.exit(status);
    }

	@Override
	public int run(String[] arg0) throws Exception {
		// TODO Auto-generated method stub
		Configuration conf = this.getConf();
		Job job = Job.getInstance(conf,this.getClass().getSimpleName());
		job.setJarByClass(this.getClass());
		
		Path inpath = new Path(arg0[0]);
		FileInputFormat.addInputPath(job, inpath);
		//map
		job.setMapperClass(MapperClass.class);
		job.setMapOutputKeyClass(WirtePair.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		//gorup
		job.setGroupingComparatorClass(GroupingComparator.class);
		job.setPartitionerClass(FirstPartitioner.class);
		//reduce
		job.setNumReduceTasks(3);
		job.setReducerClass(ReducerClass.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		
		Path outpath = new Path(arg0[1]);
		FileOutputFormat.setOutputPath(job, outpath);
		
		boolean sucess = job.waitForCompletion(true);
		return sucess? 0 : 1 ;
	}
	
	public static class FirstPartitioner extends Partitioner<WirtePair,IntWritable>{

		@Override
		public int getPartition(WirtePair key, IntWritable value, int numPartitions) {
			return (key.getFirst().hashCode() & Integer.MAX_VALUE) % numPartitions;
		}
		
	}
	
	@SuppressWarnings("rawtypes")
	public static class GroupingComparator extends WritableComparator{

		protected GroupingComparator(){
            super(WirtePair.class, true);
        }
		
		public int compare(WirtePair o1, WirtePair o2) {
			return o1.getFirst().compareTo(o2.getFirst());
		}
	}
    
	public static class MapperClass extends Mapper<LongWritable, Text, WirtePair, IntWritable> {

		private IntWritable mapOutputValue = new IntWritable();
		private WirtePair mapOutputKey = new WirtePair();
		@Override
		protected void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			// TODO Auto-generated method stub
			
			String lineValue = value.toString();
			if(lineValue.length()<2) {
				return;
			}
			// split
			String[] strs = lineValue.split(",") ;
			mapOutputKey.setFirst(strs[0]);
			mapOutputKey.setSecond(Integer.parseInt(strs[1]));
			mapOutputValue.set(Integer.parseInt(strs[1]));
			System.out.println("key:"+mapOutputKey.toString()+",value:"+mapOutputValue);
			context.write(mapOutputKey, mapOutputValue);
		}
		
	}
	public static class ReducerClass extends Reducer<WirtePair, IntWritable, Text, IntWritable>{

		@Override
		protected void reduce(WirtePair key, Iterable<IntWritable> values,
				Context context) throws IOException, InterruptedException {
			
			for(IntWritable value:values) {
				context.write(new Text(key.getFirst()),value);
			}
			
		}
		
	}
    
}

